package console

import (
	"bufio"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"go.uber.org/zap"
)

var consoleFunctions map[string]func() = make(map[string]func(), 0)

func KeepAlive() {
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	go inputListening(sigChan)
	sig := <-sigChan
	zap.L().Info("收到关闭信号，开始清理...", zap.Any("sig", sig))
}

func inputListening(sigChan chan os.Signal) {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		input := strings.TrimSpace(scanner.Text())
		if input == "exit" {
			zap.L().Info("程序退出")
			sigChan <- syscall.SIGTERM
			break
		} else {
			fun, ok := consoleFunctions[input]
			if ok {
				fun()
			}
		}
	}
}

func Register(cmd string, fun func()) {
	consoleFunctions[cmd] = fun
}
